package com.bndg.browser.db

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction

@Dao
interface HistoryDao {
    @Query("SELECT * FROM history order by timestamp desc")
    fun getAll(): MutableList<History>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(history: History)

    @Delete
    fun delete(history: History)

    @Query("SELECT * FROM history WHERE host LIKE :host and favicon <> null")
    fun queryFavicon(host: String): MutableList<History>

    @Query("SELECT * FROM history WHERE url = :url limit 1")
    fun queryHistory(url: String): History?

    @Transaction
    fun insertOrUpdate(history: History) {
        val dbHistory = queryHistory(history.url)
        dbHistory?.let {
            history.id = dbHistory.id
        }
        insert(history)
    }

    @Query("UPDATE history SET title = :title WHERE url = :url")
    fun updateHistoryTitle(title: String, url: String)
    @Query("UPDATE history SET favicon = :absolutePath WHERE host = :host")
    fun updateHistoryFavicon(absolutePath: String, host: String)
    @Query("DELETE FROM history")
    fun deleteAll()
}